package com.spzx.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.api.service.RemoteOrderInfoService;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.PaymentInfoService;
import com.spzx.payment.mapper.PaymentInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author wqdqw
* @description 针对表【payment_info(付款信息表)】的数据库操作Service实现
* @createDate 2024-11-16 09:39:21
*/
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService{

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Override
    public PaymentInfo getPaymentInfoByOrder(String orderNo) {
        //调用带条件的查询
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        //判断是否为null
        if (paymentInfo!=null){
            //查到了,证明之前已经点过立即支付了,直接返回支付记录
            return paymentInfo;
        }
        //创建PaymentInfo对象
        paymentInfo = new PaymentInfo();
        //设置属性
        paymentInfo.setOrderNo(orderNo);
        //设置支付状态为未支付
        paymentInfo.setPaymentStatus(0);
        //设置支付类型为支付宝支付,1是微信,2是支付宝
        paymentInfo.setPayType(2);
        //远程调用订单微服务根据订单号获取订单信息
        R<OrderInfo> orderInfoByOrderNo = remoteOrderInfoService.getOrderInfoByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL==orderInfoByOrderNo.getCode()){
            throw new ServiceException(orderInfoByOrderNo.getMsg());
        }
        //获取订单信息
        OrderInfo orderInfo = orderInfoByOrderNo.getData();
        //给paymentInfo设置其他属性
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        paymentInfo.setUserId(orderInfo.getUserId());
        paymentInfo.setCreateBy(orderInfo.getCreateBy());
        paymentInfo.setUpdateBy(orderInfo.getUpdateBy());
        //获取所有的订单项
        List<OrderItem> orderItemList = orderInfo.getOrderItemList();
        //使用空格拼接各个订单项的名字
        String content = orderItemList.stream().map(OrderItem::getSkuName).collect(Collectors.joining(" "));
        //设置支付内容
        paymentInfo.setContent(content);
        //插入支付记录
        baseMapper.insert(paymentInfo);

        return paymentInfo;

    }
}




